package com.wz.jiangsu.main.td;

import org.springframework.util.StopWatch;

import java.sql.*;
import java.util.Random;

public class ParameterBindingBasicDemo4 {

    private static final String host = "10.25.10.250";
    private static final Random random = new Random(System.currentTimeMillis());
    private static final int numOfRow = 10000;

    private static final String[] regions = {"east", "west", "north", "south", "center"};
    private static final String[] types = {"plc", "dcs", "ipc", "cnc", "fcs"};

    public static void main(String[] args) throws SQLException {
        String jdbcUrl = "jdbc:TAOS://" + host + ":6030/";
        Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata");

        conn.setAutoCommit(false);

        init(conn);

        String sql = "INSERT INTO single_device VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {

            StopWatch sw = new StopWatch();
            sw.start("批量插入 100000 条数据");

            for (int i = 1; i <= numOfRow; i++) {
                long current = System.currentTimeMillis() + i;
                pstmt.setTimestamp(1, new Timestamp(current));
                pstmt.setFloat(2, random.nextFloat() * 30);
                pstmt.setFloat(3, random.nextFloat() * 30);
                pstmt.setFloat(4, random.nextFloat() * 30);
                pstmt.setFloat(5, random.nextFloat() * 30);
                pstmt.setInt(6, random.nextInt(300));
                pstmt.setString(7, "host" + i);
                String randomRegion = regions[random.nextInt(5)];
                pstmt.setString(8, randomRegion);
                String randomType = types[random.nextInt(5)];
                pstmt.setString(9, randomType);
                pstmt.addBatch();

                if (i % 5000 == 0) {
                    pstmt.executeBatch();
                    conn.commit();
                }
            }
            pstmt.executeBatch();
            conn.commit();

            sw.stop();
            System.out.println("sw.prettyPrint() = " + sw.prettyPrint());

        } catch (SQLException e) {
            e.printStackTrace();
        }

        conn.close();
    }

    private static void init(Connection conn) throws SQLException {
        try (Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE DATABASE IF NOT EXISTS test");
            stmt.execute("USE test");
            stmt.execute("CREATE TABLE IF NOT EXISTS single_device (ts TIMESTAMP, cpu FLOAT, memory FLOAT, disk FLOAT, network FLOAT, processes INT, host_ip BINARY(10), region BINARY(10), type BINARY(10))");
        }
    }
}
